package com.koron.common.core.formatter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

import java.text.*;
import java.util.Date;

/**
 * @ClassName MyDateFormat
 * @description
 * @Author zhouj
 * @Date 2021/10/22 18:12
 */
@Data
@Slf4j
public class MyDateFormat extends DateFormat {

    private static final long serialVersionUID = 1L;

    private DateFormat dateFormat;

    private SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public MyDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
        this.calendar = dateFormat.getCalendar();
        this.numberFormat = dateFormat.getNumberFormat();
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return dateFormat.format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {

        Date date = null;

        try {

            date = format1.parse(source, pos);
        } catch (Exception e) {

            date = dateFormat.parse(source, pos);
        }

        return date;
    }

    // 主要还是装饰这个方法
    @Override
    public Date parse(String source) throws ParseException {

        Date date = null;

        try {
            // 先按我的规则来
            //date = format1.parse(source);
            date = convert(source);
        } catch (Exception e) {
            // 不行，那就按原先的规则吧
            date = dateFormat.parse(source);
        }

        return date;
    }

    public Date convert(String str) {
        String[] patterns = new String[]{
                "yyyy-MM-dd",
                "yyyy-MM-dd HH:mm:ss",
                "yyyy-MM-dd HH:mm",
                "yyyy/MM/dd",
                "yyyy/MM/dd HH:mm:ss",
                "MM-dd-yyyy",
                "dd-MM-yyyy",
                "yyyy",
                "yyyy-MM"
        };
        try {
            Date date = DateUtils.parseDate(str, patterns);
            return date;
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    // 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new MyDateFormat((DateFormat) format);
    }
}
